package com.ht.api.task.ad;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.*;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.open.OpenUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.*;

/**
 * 拉取朋友圈互动数据
 */
@Slf4j
public class PullMomentCommentTask implements TaskHandler {
    /** 接口ID：获取客户朋友圈的互动数据*/
    protected static final long API_ID = 1900861434246598656L;

	@Override
	public String getName() {
		return "拉取朋友圈互动数据";
	}

    @Override
    public boolean handler(JSONObject requestParam, String groupId, long taskId) {
        long tenantId = requestParam.getLong("tenant_id");
        DataSource ds = DbConfig.useTenantDb(tenantId);
        StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);


        String adTaskGroupId = requestParam.getStr("ad_task_group_id");

        String momentId = requestParam.getStr("moment_id");
        String userid = requestParam.getStr("userid");
        String appid = requestParam.getStr("appid");

        JSONObject param = JSONUtil.createObj();
        param.set("moment_id", momentId);
        param.set("userid", userid);

        String str = OpenUtil.call(appid, API_ID, param);
        JSONObject result = JSONUtil.parseObj(str);

        DbList likeCustomerList = Db.query(ds, "select openid from wx_moment_customer where like_time is null and userid = ? and ad_task_group_id = ?", userid, adTaskGroupId);
        DbList commentCustomerList = Db.query(ds, "select openid from wx_moment_customer where comment_time is null and userid = ? and ad_task_group_id = ?", userid, adTaskGroupId);

        Entity task = Db.createSqlParser("ad_user_task").where("ad_task_group_id", adTaskGroupId).findOne(ds);


        Set<String> likeCustomers = new HashSet<>();
        for (Entity entity : likeCustomerList) {
            likeCustomers.add(entity.getStr("openid"));
        }

        Set<String> commentCustomers = new HashSet<>();
        for (Entity entity : commentCustomerList) {
            commentCustomers.add(entity.getStr("openid"));
        }

        List<Entity> dataList = new ArrayList<>();

        JSONArray likeList = result.getJSONArray("like_list");
        for (int i = 0; i < likeList.size(); i++) {
            JSONObject like = likeList.getJSONObject(i);
            if (like.containsKey("userid")) {
                continue;
            }

            if (!likeCustomers.contains(like.get("external_userid"))) {
                continue;
            }

            Entity momentCustomer = Entity.create("wx_moment_customer");
            momentCustomer.set("ad_task_group_id", adTaskGroupId);
            momentCustomer.set("userid", userid);
            momentCustomer.set("openid", like.get("external_userid"));
            momentCustomer.set("like_time", DateUtil.format(new Date(like.getLong("create_time")*1000), "yyyy-MM-dd HH:mm:ss"));

            dataList.add(momentCustomer);

            Entity userEventLog = Entity.create("user_event_log");
            userEventLog.set("openid", like.get("external_userid"));
            userEventLog.set("event_type", "moment");
            userEventLog.set("event_key", "like");
            userEventLog.set("relation_id", task.get("ad_id"));
            userEventLog.set("event_time", momentCustomer.getStr("like_time"));

            JSONObject context = buildContext(task);

            userEventLog.set("context", context);

            dataList.add(userEventLog);

        }


        JSONArray commentList = result.getJSONArray("comment_list");
        for (int i = 0; i < commentList.size(); i++) {
            JSONObject comment = commentList.getJSONObject(i);
            if (comment.containsKey("userid")) {
                continue;
            }

            if (!commentCustomers.contains(comment.get("external_userid"))) {
                continue;
            }

            Entity momentCustomer = Entity.create("wx_moment_customer");
            momentCustomer.set("ad_task_group_id", adTaskGroupId);
            momentCustomer.set("userid", userid);
            momentCustomer.set("openid", comment.get("external_userid"));
            momentCustomer.set("comment_time", DateUtil.format(new Date(comment.getLong("create_time")*1000), "yyyy-MM-dd HH:mm:ss"));

            dataList.add(momentCustomer);

            Entity userEventLog = Entity.create("user_event_log");
            userEventLog.set("openid", comment.get("external_userid"));
            userEventLog.set("event_type", "moment");
            userEventLog.set("event_key", "comment");
            userEventLog.set("relation_id", task.get("ad_id"));
            userEventLog.set("event_time", momentCustomer.getStr("comment_time"));

            JSONObject context = buildContext(task);

            userEventLog.set("context", context);

            dataList.add(userEventLog);
        }

        Db.insertBatchWithStream(config, dataList);

        log.info("拉取互动数据 success......");

        return true;
    }


    public JSONObject buildContext (JSONObject task) {
        JSONObject context = JSONUtil.createObj();
        context.set("openid", task.get("openid"));
        context.set("ad_id", task.get("ad_id"));

        if (task.getInt("touch") == 1) {
            context.set("userid", task.get("touch_id"));
        } else if (task.getInt("touch") == 2) {
            context.set("chat_id", task.get("touch_id"));
        }

        context.set("plan_id", task.get("plan_id"));
        context.set("creative_id", task.get("creative_id"));

        return context;
    }
}
